<template>

	<view>
		<view class="content">
			<z-paging ref="paging" :refresher-only="true" :fixed="true" :show-loading-more-no-more-view='false'
				:refresher-enabled="false" :refresher-threshold="0" hide-refresher-when-reload
				hide-refresher-when-enabled>
				<template #top>

					<m-drag-button :style="{ opacity: BtnShow ? 1 : 0, }" :isDock="true" :existTabBar="true"
						:initialBottom="160" @btnClick="scan">
						<template #BtnContent>
							<u-icon name="scan" color="#fff" size="54rpx"></u-icon>
						</template>
					</m-drag-button>

					<u-navbar :fixed="false" title="设备保养" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff"
						@leftClick='leftClick'></u-navbar>
				</template>

				<view class="MainBox">
					<u--form labelPosition="left" :model="baseFormData" :rules="rules" ref="uForm">

						<u-form-item labelWidth="100" label="保养编号" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="order">
							<u--input v-model="baseFormData.BillNO" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="设备" borderBottom :leftIconStyle="{'font-size':'20px'}"
							prop="EquipmentName" required leftIcon="file-text" @click="openBaseScreen('设备', 'radio')">
							<u--input v-model="baseFormData.EquipmentName" placeholder="请选择设备" readonly
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-form-item labelWidth="100" label="保养人员" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="order">
							<u--input v-model="baseFormData.UpkeepMan" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="开始时间" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="calendar">
							<u--input v-model="baseFormData.StartMaintenance" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="结束时间" borderBottom :leftIconStyle="{'font-size':'20px'}"
							leftIcon="calendar">
							<u--input v-model="baseFormData.EndMaintenance" placeholder="自动生成" readonly
								border="none"></u--input>
						</u-form-item>
						<u-form-item labelWidth="100" label="保养周期" :leftIconStyle="{'font-size':'20px'}"
							prop="PeriodTypeName" required leftIcon="file-text" @click="openBaseScreen('周期', 'radio')">
							<u--input v-model="baseFormData.PeriodTypeName" placeholder="自动生成" readonly
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
					</u--form>


					<view class="Main_CardListBox">
						<view class="CardBox" v-for="(item,index) in tableData" :key="index">
							<view class="Main_Card_Top">
								<view class="Main_Card_LeftBox x-f">
									<view class="OrdinalBox">
										<text>{{index + 1}}</text>
									</view>
									<view class="Title_Text x-f">
										<text>保养项目</text>
									</view>
								</view>
							</view>
							<view class="CommonBox">
								<u-cell title="保养项目">
									<template #value>
										<div class="CommonBoxDiv" :style="{ width: scrollLiftWidth + 'px'}">
											{{item.UpkeepItemName}}
										</div>
									</template>
								</u-cell>
								<u-cell title="保养结果" :border='false' class="custom-cell">
									<template slot="right-icon">
										<uni-data-checkbox v-model="item.FResult" :localdata="sexs"
											:disabled="!submitButtonShow" />
									</template>
								</u-cell>
							</view>

						</view>
					</view>


				</view>
				<template #bottom>
					<view class="BottomBox" :style="$utils.disposeSafeBottomFun()" v-show="submitButtonShow">
						<button block @click="submit" style="width: 90%;margin: 0 auto !important;"
							class="content_bottom_primary_Btn">
							{{submitButton}}
						</button>
					</view>

				</template>
			</z-paging>

		</view>
		<u-popup :show="popup_logout" mode="center" :closeOnClickOverlay="false" :round="4">
			<view class="popup-content">
				<view class="popup-content_close x-c">
					<uni-icons type="closeempty" color="#999" size="20" @click='popup_logout = false'></uni-icons>
				</view>
				<view class="x-c title">
					<text>{{popuptitle}}</text>
				</view>
				<view class="contentView">
					<text>{{popupcontent}}</text>
				</view>
				<view class="btnBox x-ac">
					<u-button type="primary" text="确定" @click="popup_logout = false"></u-button>
				</view>
			</view>
		</u-popup>
		<u-toast ref="uToast"></u-toast>
	<m-pda-scancode v-if="$utils.isPda()" listenName="BatchEditScan"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>
	</view>


</template>

<script>
	import {
		getFormatDateTime,
		getBefore7DateTime
	} from '@/st_device/common/base.js';
	export default {
		data() {
			return {
				popup_logout: false,
				popuptitle: '提示',
				popupcontent: '',
				BtnShow: false,
				rules: {
					'EquipmentName': {
						type: 'string',
						required: true,
						message: '设备不能为空',
						trigger: ['change']
					},
					'PeriodTypeName': {
						type: 'string',
						required: true,
						message: '保养周期不能为空',
						trigger: ['change']
					}
				},
				baseFormData: {
					EquipmentName: '',
					EquipmentID: '',
					PeriodTypeName: '周',
					PeriodType: 'W',
					UpkeepMan: '',
					BillDate: '',
				},
				sexs: [],

				PeriodTypeList: [],
				tableData: [],
				Timeshow: false,
				value1: Number(new Date()),
				submitButton: '',
				submitButtonShow: true,
				scrollLiftWidth: uni.getSystemInfoSync().windowWidth, //列表高度
			};
		},
		onUnload() {
			uni.$off('BatchEditScan');
			uni.$off('maintenanceDetail_Choice');
			console.log('触发');
		},


		onLoad(item) {
			var that = this
			console.log(item);
			var EquipmentObj
			if (item.EquipmentObj) {
				EquipmentObj = JSON.parse(item.EquipmentObj)
			}
			that.Request.request('getPeriodTypeSet', {}, (ret) => {
				that.PeriodTypeList = ret.data.ds
			})
			that.Request.request('GetResultSelect', {
				FType: '保养结果'
			}, (ret) => {
				ret.data.ds.map(item => {
					item.text = item.NAME
					item.value = item.ID
				})
				that.sexs = ret.data.ds
			})
			if (item.UpkeepEquipmentID) {
				that.queryList(item.UpkeepEquipmentID)
			} else {
				that.submitButton = '开始保养'
				this.baseFormData.UpkeepMan = this.baseFormData.UpkeepMan ? this.baseFormData.UpkeepMan : this
					.$store.state.UserInfo.UserName
				this.baseFormData.CheckupID = this.baseFormData.CheckupID ? this.baseFormData.CheckupID : this.$store
					.state.UserInfo.EmplID
				if (EquipmentObj) {
					this.baseFormData.EquipmentName = this.baseFormData.EquipmentName ? this.baseFormData.EquipmentName :
						EquipmentObj.EquipmentName
					this.baseFormData.EquipmentID = this.baseFormData.EquipmentID ? this.baseFormData.EquipmentID :
						EquipmentObj.EquipmentID
					that.addPeriodTypeClick()
				}
				this.baseFormData.BillDate = this.baseFormData.BillDate ? this.baseFormData.BillDate :
					getFormatDateTime(new Date())
				if (item.EquipmentID && item.PeriodType) {
					that.Request.request('getEquipment', {}, (ret) => {
						if (ret.status == 200) {
							var obj = ret.data.ds.find(ite => ite.EquipmentID == item.EquipmentID)
							that.baseFormData.EquipmentName = obj.EquipmentName
							that.baseFormData.EquipmentID = obj.EquipmentID
							that.baseFormData.PeriodType = item.PeriodType
							that.addPeriodTypeClick()
						}
					})

				}

			}
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		mounted() {
			var that = this
			// PDA扫码处理
			uni.$on('BatchEditScan', function(content) {
				let scanData = that.$utils.wmsFun.scanTransf(content);
				that.scanHandler(scanData);
			})
			that.$nextTick(() => {
				that.scrollLiftWidth = (uni.getSystemInfoSync().windowWidth) / 3
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
			uni.$on('maintenanceDetail_Choice', function(ret) {
				console.log(ret);
				if (ret.type == '周期') {
					that.baseFormData.PeriodType = ret.data.ID
					that.baseFormData.PeriodTypeName = ret.data.NAME
					that.$refs.uForm.validateField('PeriodTypeName');
					that.PeriodTypeClick()
				} else if (ret.type == '设备') {
					that.baseFormData.EquipmentName = ret.data.EquipmentName
					that.baseFormData.EquipmentID = ret.data.EquipmentID
					that.$refs.uForm.validateField('EquipmentName');
					that.PeriodTypeClick()
				}

			});
		},
		methods: {
			scanHandler(scanData) {
				let that = this;
				console.log(scanData);
				that.DeviceIDChange(scanData.recode, 'pda')
			},
			DeviceIDChange(res, name) {
				let that = this;
			
				function startsWithEQRegex(str) {
					return /^EQ/.test(str) || /^SB/.test(str);
				}
				let IsDevice = startsWithEQRegex(res)
				if (IsDevice) {
					var id = res.replace(/^.*?\|/, '')
					console.log(id);
					that.Request.request('getEquipment', {}, (ret) => {
						console.log(ret);
						if (ret.status == 200) {
							var obj = ret.data.ds.find(item => item.EquipmentID == id)
							var url = `./maintenanceDetail?EquipmentObj=${JSON.stringify(obj)}`
							uni.redirectTo({
								url: url
							});					
						}
					})
				}
			},
			openBaseScreen(str, type) { // 前往筛选页
				let that = this;
				let obj = null;
				let url = '/commonPage/Tool/baseScreen';
				if (this.submitButtonShow) {

					if (str == '设备') {
						obj = {
							allowClear: false,
							cmd: 'getEquipment',
							type: str,
							ListeningName: 'maintenanceDetail_Choice',
							serverSearch: {
								isPaging: false, //是否分页
								searchKey: 'EquipmentName', //搜索关键词，应包含在param中
								showText: 'EquipmentName', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								ChoiceDataKey: 'EquipmentID',
								ChoiceDataData: that.baseFormData.EquipmentID,
							},
							param: {
								EquipmentName: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					} else if (str == '周期') {
						obj = {
							allowClear: false,
							cmd: 'getPeriodTypeSet',
							type: str,
							ListeningName: 'maintenanceDetail_Choice',
							serverSearch: {
								isPaging: false, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								showText: 'NAME', //查询结果显示的字段
								pageIndexStr: 'PageIndex', //分页页码字段，应包含在param中
								ChoiceDataKey: 'ID',
								ChoiceDataData: that.baseFormData.PeriodType,
							},
							param: {
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						}
					}
					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'BaseScreenParm',
						data: obj
					})
					uni.navigateTo({
						url: url
					})
				}

			},
			addPeriodTypeClick() {
				var that = this
				that.Request.request('getPeriodTypeSet', {}, (ret) => {
					that.PeriodTypeList = ret.data.ds
					console.log(that.PeriodTypeList);
					var obj = that.PeriodTypeList.find(item => item.ID == that.baseFormData.PeriodType)
					that.baseFormData.PeriodTypeName = obj.NAME
					that.PeriodTypeClick()
				})

			},
			PeriodTypeClick() {
				var that = this
				if (that.baseFormData.EquipmentID) {
					var obj = {
						EquipmentID: that.baseFormData.EquipmentID,
						PeriodType: that.baseFormData.PeriodType,
						FType: 'SBBY'
					}
					console.log(obj);
					that.Request.request('getCheckupItem', obj, (ret) => {
						console.log(ret);
						ret.data.ds.map((item) => {
							item.FResult = item.FResult ? item.FResult : 1
							item.UpkeepEquipmentDeID = item.UpkeepEquipmentDeID ? item
								.UpkeepEquipmentDeID : 0

						})
						that.tableData = ret.data.ds
						that.$forceUpdate()
					})

				}
			},
			getBYStatus(val) {
				var obj = this.PeriodTypeList.find(item => item.ID == val)
				return obj.NAME
			},
			scan() {
				let that = this;
				uni.scanCode({
					success: function(res) {
						console.log(res);
						that.DeviceIDChange(res.result, 'phone')
					},
					fail: function(fail) {
						console.log(fail);
					}
				});

			},

			pickerConfirm(e) {
				var time = getFormatDateTime(e.value)
				this.baseFormData.BillDate = time
				this.Timeshow = false
				this.$forceUpdate()
			},


			submit() {
				var that = this
				var show = true
				var msg
				this.$refs.uForm.validate().then(res => {
					if (that.tableData.length == 0) {
						show = false
						msg = '当前设备没有该保养周期'
					}
					if (show) {
						var obj = {
							UpkeepMan: that.baseFormData.UpkeepMan,
							EquipmentID: that.baseFormData.EquipmentID,
							UpkeepEquipmentID: that.baseFormData.UpkeepEquipmentID ? that.baseFormData
								.UpkeepEquipmentID : 0,
							PeriodType: that.baseFormData.PeriodType,
							UpID: that.tableData.map(item => item.UpID).join(','),
							UpkeepItemID: that.tableData.map(item => item.UpkeepItemID).join(','),
							FResult: that.tableData.map(item => item.FResult).join(','),
							BillDate: that.baseFormData.BillDate,
							UpkeepItemContent: that.tableData.map(item => item.UpkeepItemContent).join(','),
							UpkeepEquipmentDeID: that.tableData.map(item => item.UpkeepEquipmentDeID).join(
								','),
							FType: 'SBBY',
							ApproveMan: that.$store.state.UserInfo.UserName
						}
						console.log(obj);

						that.Request.request('saveUpkeepEquipment', obj, function(ret) {
							console.log(ret);
							if (ret.status == 200) {
								that.$refs.uToast.show({
									title: '保存',
									type: 'success',
									message: '保存成功'
								})
								that.queryList(ret.data.ds[0].UpkeepEquipmentID)
							}
						})
					} else {
						that.popup_logout = true
						that.popupcontent = msg
					}

				}).catch(errors => {
					uni.$u.toast(errors[0].message)
				})

			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getUpKeepEquipmentDetail', {
						UpkeepEquipmentID: id
					}, (ret) => {
						console.log(ret.data);
						ret.data.ds.map((item) => {
							if (item.PeriodType) {
								item.PeriodTypeName = item.PeriodTypeName ? item.PeriodTypeName : that
									.getBYStatus(item.PeriodType)
							}

						})
						that.baseFormData = ret.data.ds[0]
						that.baseFormData.StartMaintenance = that.baseFormData.StartMaintenance ? that.baseFormData
							.StartMaintenance.replace('T', ' ').split('.')[0] : ''
						that.baseFormData.EndMaintenance = that.baseFormData.EndMaintenance ? that.baseFormData
							.EndMaintenance.replace('T', ' ').split('.')[0] : ''
						that.tableData = ret.data.ds1
						that.$forceUpdate()
						if (that.baseFormData.BYStatus == 0) {
							that.submitButton = '开始保养'
						} else if (that.baseFormData.BYStatus == 1) {
							that.submitButton = '结束保养'
						} else {
							// that.submitButton = '已结束保养'
							that.submitButtonShow = false
						}
					})
				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			changeLevel(data, row) {
				let routes = getCurrentPages(); //当前页面栈
				let backIndex = routes.length - row.length; // 计算返回页面栈数

				if (backIndex == 1) {
					let prevPage = routes[routes.length - 2]
					prevPage.$vm.getList()
				}
				uni.navigateBack({
					delta: backIndex
				})
			},

			leftClick() {
				let routes = getCurrentPages(); //当前页面栈
				let prevPage = routes[routes.length - 2]
				prevPage.$vm.getList()
			}
		}
	}
</script>

<style lang="scss">
	@import "./css/index.css";

	.Main_CardListBox {
		padding: 10px 15px;

		.CardBox {
			position: relative;
			margin-bottom: 20rpx;
			background-color: #fff;
			padding: 15px;
			overflow: hidden;
			border-radius: 12px;
			// min-height: 300px;
			box-shadow: 0 0 8px -7px #333;

			.Xuhao_YL {
				position: absolute;
				left: 0;
				top: 0;
				min-width: 24px;
				height: 24px;
				line-height: 24px;
				background-color: #51d0d0;
				border-radius: 0 0 10px 0;
				text-align: center;
				color: #fff;
			}

			.Main_Card_Top {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.OrdinalBox {
					width: fit-content;
					min-width: 24px;
					height: 24px;
					border-radius: 9999px;
					background-color: #51d0d0;
					color: #fff;
					font-size: 14px;
					line-height: 24px;
					text-align: center;
				}

				.Title_Text {
					margin-left: 6px;
					font-weight: 600;
					font-size: 24rpx;
				}
			}

			.CommonBox {
				border-radius: 8px;
				background-color: #f7f7f7;
				padding: 10px 0px;
				margin-top: 15px;

				.CommonBoxDiv {
					word-wrap: break-word;
					// direction: rtl;
				}

				.custom-cell {
					background-color: transparent !important;
					color: inherit !important;

					.uni-data-checklist .checklist-group ::v-deep .checklist-box {
						margin-right: 5px !important;
					}
				}

				.TextBox {
					font-size: 24rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					flex: 1;
				}


				.LeftIcon {
					width: 30px;
					height: 30px;
					line-height: 30px;
					font-size: 18px;
					border-radius: 8px;
					color: #fff;
					background-color: #01b87d;
					text-align: center;
				}


			}

			.ShowSigningWork {
				display: flex;
				justify-content: flex-end;
				align-items: center;
				margin-top: 10px;

				.button {
					padding: 0rpx 10rpx;
					border-radius: 99999px;
					min-width: 120px;
					background-color: #fff;
					zoom: .8;
					margin-left: 6px !important;
				}
			}
		}
	}



	.content {
		display: flex;
		flex-direction: column;
		height: 100vh;
		// height: calc(100vh - 60px);
		background-color: #f9f9f9;

		uni-button {
			margin-left: initial !important;
			margin-right: initial !important;
		}

		.MainPopup {
			flex: initial !important;

			.PopupContent {
				display: flex;
				flex-direction: column;
				min-height: 240px;
				width: 90vw;
			}

			.u-transition {
				z-index: 99999 !important;
			}


			.PopupMainBox {
				padding: 12px 10px 6px;
				flex: 1;
				// overflow: auto;

				.CellBox {
					margin-bottom: 20px;

					.LeftBox {
						font-size: 14px;
						color: #999;
						margin-right: 10px;
					}
				}

				.uni-input-placeholder {
					color: #6a6a6a !important;
					font-size: 12px !important;
				}
			}

			.PopupBottomBox {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 10px 10px;

				.CancelBtn {
					background-color: #fff;
					color: #51d0d0;
					border: 1px solid #51d0d0;
					min-width: 80px;
				}

				.ComfirmBtn {
					background-color: #51d0d0;
					color: #fff;
					min-width: 80px;
					margin-left: 10px !important;
				}
			}
		}

		.MainBox {
			flex: 1;
			overflow: auto;
			// padding: 10px;

			// 表单1
			.u-form {
				// padding: 0px 10px;

				.u-form-item {
					background-color: #fff;
					padding: 0 16px;
				}


				.TopOption {

					.u-form-item__body {
						flex-direction: column !important;
					}
				}

				// 起止时间
				.ChoiceTimesBox {
					width: 100%;
					display: flex;
					align-items: center;
					// background-color: #fff;
					// padding: 18px 10px;
					// margin-top: 10px;

					.TimeBox {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: space-evenly;

						.timer {
							width: 100%;
							flex: 2;
							display: flex;
							flex-direction: column;
							// align-items: center;
							font-size: 14px;
							color: #333;

							text:first-child {
								margin-bottom: 10px;
								font-weight: 600;
							}

							text:last-child {
								height: 20px;
							}
						}

						.Icon {
							flex: 1;
						}
					}
				}


				// 上传-删除图标
				.u-upload__deletable {
					width: 20px;
					height: 20px;

					.u-upload__deletable__icon {
						right: -1px !important;

						.u-icon__icon {
							font-size: 20px !important;
							line-height: 16px !important;
						}
					}
				}
			}
		}

		.BottomBox {
			width: 100%;
			border-top: 1px solid #efefef;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: #fff;
		}
	}
</style>